package com.nerve.android.cloudoffice.app.activity;

import org.nerve.android.annotation.Acvitity;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Handler;

import com.nerve.android.cloudoffice.OfficeApplication;
import com.nerve.android.cloudoffice.R;
import com.nerve.android.cloudoffice.app.NavigationActivity;
import com.nerve.android.cloudoffice.app.group.IndexGroupActivity;
import com.nerve.android.cloudoffice.app.worker.LoginWorker;
import com.nerve.android.cloudoffice.common.Const;

/**
 * @project: Cloudoffice
 * @file: AutoLoginActivity.java
 * @package: com.nerve.android.cloudoffice.app.activity
 * @description:
 *
 * @author: 集成显卡	1053214511@qq.com
				IBM GDC, zengxm@cn.ibm.com
 * @date&time: Aug 15, 2013
 * @change log:
 */
@SuppressLint("HandlerLeak")
@Acvitity(layout=R.layout.activity_auto_login)
public class AutoLoginActivity extends NavigationActivity{
	public static final String SHARED_FILE = "love_ydt";
	public static final String NAME = "name";
	public static final String PASSWORD = "password";
	public static final String AUTO = "auto_login";
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case WORKER_FAIL:
				toast(Const.ERROR);
				toLogin();
				break;
			case WORKER_OK:
				Const.log("----------自动登录成功---------");
				toActivity(IndexGroupActivity.class, true);
				finish();
				break;
			}
		}
	};
	
	@Override
	protected void initUI() {
		super.initUI();
		showNavigate(false);
		
		SharedPreferences sp = getSharedPreferences(SHARED_FILE, MODE_PRIVATE);
		
		//
		String sessionId = sp.getString("JSESSIONID", "");
		OfficeApplication.JSESSIONID = sessionId;
		Const.log("*****Load sessionId:"+sessionId+"****");
		
		//用户不为空，且上一次登录时间在30分钟以内，则自动登录
		if(OfficeApplication.USER != null
				&& System.currentTimeMillis()-OfficeApplication.LAST_LOGIN_TIME < 30*60*1000){
			Const.log("----------已经登录了---------");
			toActivity(IndexGroupActivity.class, true);
			finish();
			return ;
		}
		
		Const.log("判断是否自动登录！！！！！！！！！！");
		
		if(sp.getBoolean(AUTO, false)){
			//获取用户名和密码
			String name = sp.getString(NAME, null);
			String password = sp.getString(PASSWORD, null);
			
			if(name != null && password != null){
				new LoginWorker(handler).execute(name, password);
			}else{
				toLogin();
			}
		}else{
			Const.log("直接跳转到LoginActivity！");
			toLogin();
		}
	}
	
	private void toLogin(){
		toActivity(LoginActivity.class, true);
		finish();
	}
}